<template>
	<view class="detail-advance-page">
		<!-- 自定義導航欄 -->
		<u-navbar
			title="详情"
			:border="false"
			:auto-back="true"
			:bg-color="'#FFFFFF'"
			:title-color="'#333333'"
			:title-size="36"
			:title-weight="'bold'"
			placeholder
		>
			<template #right>
				<u-icon name="more-dot-fill" size="20" color="#333" @click="showMoreOptions"></u-icon>
				<u-icon name="search" size="20" color="#333" @click="showSearch" style="margin-left: 20rpx;"></u-icon>
			</template>
		</u-navbar>

		<!-- 详情内容 -->
		<view class="detail-content">
			
			<!-- 事由 -->
			<view class="detail-section">
				<view class="section-header">
					<text class="section-title">事由</text>
				</view>
				<view class="detail-field">
					<text class="detail-text">{{ advanceDetail.reason }}</text>
				</view>
			</view>

			<!-- 借款明细 -->
			<view class="detail-section">
				<view class="section-header">
					<text class="section-title">借款明细</text>
				</view>
				<view 
					v-for="(item, index) in advanceDetail.loanDetails" 
					:key="index"
					class="loan-detail-item"
				>
					<view class="detail-header">
						<text class="detail-number">({{ index + 1 }}) 借款明细</text>
					</view>
					
					<!-- 费用项目 -->
					<view class="detail-field">
						<text class="field-label">费用项目</text>
						<view class="detail-value">
							<text class="detail-text">{{ item.expenseItem }}</text>
						</view>
					</view>
					
					<!-- 借款金额 -->
					<view class="detail-field">
						<text class="field-label">借款金额</text>
						<view class="detail-value">
							<text class="detail-text">{{ item.loanAmount }}</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 附件 -->
			<view class="detail-section">
				<view class="section-header">
					<text class="section-title">附件</text>
				</view>
				<view class="attachments-area">
					<view v-if="advanceDetail.attachments.length === 0" class="no-attachments">
						<text class="no-attachments-text">暂无附件</text>
					</view>
					<view v-else class="attachments-list">
						<view 
							v-for="(file, index) in advanceDetail.attachments" 
							:key="index"
							class="file-item"
							@click="previewImage(file)"
						>
							<!-- 图片缩略图 -->
							<image 
								v-if="isImageFile(file.name)" 
								:src="getImageUrl(file)" 
								class="file-thumbnail"
								mode="aspectFill"
							/>
							<!-- 文件图标 -->
							<view v-else class="file-icon">
								<text class="icon-text">📎</text>
							</view>
							<!-- 文件信息 -->
							<view class="file-info">
								<text class="file-name">{{ file.name }}</text>
								<text class="file-size" v-if="file.fileSize">{{ formatFileSize(file.fileSize) }}</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 底部安全区域 -->
		<view class="safe-area-bottom"></view>
		
		<!-- 编辑按钮 - 只有"开立"状态才显示 -->
		<view v-if="canEdit" class="edit-button-container">
			<button class="edit-button" @click="goToEdit">
				编辑
			</button>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { borrowApi } from '@/api/api-helper.js'

// API基础URL常量
const API_BASE_URL = 'https://hongjiang.hj-hr.com'

// 预支详情数据
const advanceDetail = reactive({
	id: '',
	reason: '',
	loanDetails: [],
	attachments: [],
	billStatus: '' // 添加借款状态字段
})

// 页面参数
const pageParams = ref({
	id: '',
	status: '', // 前端状态值：pending, submitted, approved
	billStatus: '', // 后端状态值：0, 2, 4
	statusText: '' // 状态文字：开立, 提交, 生效
})

// 计算是否可以编辑 - 只有"开立"状态才能编辑
const canEdit = computed(() => {
	// 优先使用传递过来的状态参数，如果没有则使用详情数据中的状态
	const currentBillStatus = pageParams.value.billStatus || advanceDetail.billStatus
	return currentBillStatus === '0' // 0: 开立
})

// 加载详情数据
const loadDetailData = async () => {
	if (!pageParams.value.id) return
	
	try {
		const response = await borrowApi.getBorrowDetail(pageParams.value.id)
		if (response.code === 200) {
			const data = response.data
			
			// 更新详情数据
			advanceDetail.id = data.id || ''
			advanceDetail.reason = data.description || ''
			advanceDetail.billStatus = data.billStatus || '' // 更新借款状态
			
			// 加载借款明细
			if (data.borrowItemVOList && data.borrowItemVOList.length > 0) {
				advanceDetail.loanDetails = data.borrowItemVOList.map(item => ({
					expenseId: item.expenseId || '', // 保持 expenseId 存储
					expenseItem: item.expenseName || item.expenseId || '', // 优先显示 expenseName，没有则显示 expenseId
					loanAmount: item.amount ? String(item.amount) : ''
				}))
			} else {
				advanceDetail.loanDetails = []
			}
			
			// 加载附件
			if (data.attachment) {
				try {
					const attachmentData = JSON.parse(data.attachment)
					// 处理附件数据，支持嵌套数组格式
					let processedAttachments = []
					if (Array.isArray(attachmentData)) {
						// 如果是数组，处理可能的嵌套情况
						attachmentData.forEach(item => {
							if (Array.isArray(item)) {
								// 嵌套数组，展开
								processedAttachments.push(...item)
							} else {
								// 直接添加
								processedAttachments.push(item)
							}
						})
					} else {
						processedAttachments = [attachmentData]
					}
					
					// 过滤有效的附件数据
					advanceDetail.attachments = processedAttachments.filter(att => 
						att && att.name && (att.url || att.thumbUrl)
					)
					
					console.log('解析后的附件数据:', advanceDetail.attachments)
				} catch (e) {
					console.error('解析附件数据失败:', e)
					advanceDetail.attachments = []
				}
			} else {
				advanceDetail.attachments = []
			}
			
			console.log('已加载详情数据:', advanceDetail)
		} else {
			uni.showToast({
				title: response.msg || '加载详情失败',
				icon: 'none'
			})
		}
	} catch (error) {
		console.error('加载详情数据失败:', error)
		uni.showToast({
			title: '网络错误',
			icon: 'none'
		})
	}
}

// 页面加载时获取参数
onLoad((options) => {
	console.log('=== onLoad 触发 ===')
	console.log('页面参数 options:', options)
	
	// 直接从 options 获取参数
	if (options) {
		pageParams.value.id = options.id || ''
		pageParams.value.status = options.status || ''
		pageParams.value.billStatus = options.billStatus || ''
		pageParams.value.statusText = options.statusText ? decodeURIComponent(options.statusText) : ''
	}
	
	console.log('详情页面加载完成，pageParams:', pageParams.value)
	console.log('状态信息:', {
		status: pageParams.value.status,
		billStatus: pageParams.value.billStatus,
		statusText: pageParams.value.statusText
	})
})

// 页面显示时加载数据
onShow(() => {
	console.log('=== onShow 触发 ===')
	console.log('页面参数 pageParams:', pageParams.value)
	
	// 每次页面显示时都重新加载详情数据
	if (pageParams.value.id) {
		loadDetailData()
	}
})

// 获取状态样式类
const getStatusClass = (statusText: string) => {
	switch (statusText) {
		case '生效':
			return 'status-active'
		case '提交':
			return 'status-pending'
		case '开立':
			return 'status-default'
		default:
			return 'status-default'
	}
}

// 判断是否为图片文件
const isImageFile = (fileName: string) => {
	if (!fileName) return false
	const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']
	const lowerFileName = fileName.toLowerCase()
	return imageExtensions.some(ext => lowerFileName.endsWith(ext))
}

// 获取图片URL
const getImageUrl = (file: any) => {
	// 优先使用缩略图，如果没有则使用原图
	let imageUrl = file.thumbUrl || file.url || ''
	
	// 如果URL是相对路径，添加基础URL前缀
	if (imageUrl && !imageUrl.startsWith('http')) {
		imageUrl = API_BASE_URL + imageUrl
	}
	
	return imageUrl
}

// 格式化文件大小
const formatFileSize = (bytes: number) => {
	if (bytes === 0) return '0 B'
	const k = 1024
	const sizes = ['B', 'KB', 'MB', 'GB']
	const i = Math.floor(Math.log(bytes) / Math.log(k))
	return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 预览图片
const previewImage = (file: any) => {
	if (!isImageFile(file.name)) {
		uni.showToast({
			title: '该文件不是图片，无法预览',
			icon: 'none'
		})
		return
	}
	
	const imageUrl = getImageUrl(file)
	if (!imageUrl) {
		uni.showToast({
			title: '图片地址无效',
			icon: 'none'
		})
		return
	}
	
	console.log('预览图片URL:', imageUrl)
	
	// 使用uni-app的图片预览功能
	uni.previewImage({
		current: imageUrl,
		urls: [imageUrl],
		success: () => {
			console.log('图片预览成功')
		},
		fail: (error) => {
			console.error('图片预览失败:', error)
			uni.showToast({
				title: '图片预览失败',
				icon: 'none'
			})
		}
	})
}

// 方法
const showMoreOptions = () => {
	uni.showActionSheet({
		itemList: ['分享', '导出', '设置'],
		success: (res) => {
			console.log('选择了:', res.tapIndex)
		}
	})
}

const showSearch = () => {
	uni.showToast({
		title: '搜索功能',
		icon: 'none'
	})
}

const goToEdit = () => {
	// 跳转到新增页面，传入id参数使其变成编辑模式
	uni.navigateTo({
		url: `/pages/advance/add?id=${advanceDetail.id}`
	})
}
</script>

<style lang="scss" scoped>
.detail-advance-page {
	background-color: #F5F5F5;
	min-height: 100vh;
	padding-bottom: 120rpx;
	:deep(.u-swipe-action-item){
		margin-right:40rpx !important;
	}
}

/* 详情内容 */
.detail-content {
	padding: 20rpx;
	padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
}

/* 状态显示样式 */
.status-display {
	padding: 20rpx;
	background-color: #FFFFFF;
	border-radius: 8rpx;
	border: 1rpx solid #E0E0E0;
}

.status-text {
	font-size: 32rpx;
	font-weight: bold;
	padding: 10rpx 20rpx;
	border-radius: 20rpx;
	
	&.status-active {
		background-color: #4CAF50;
		color: #FFFFFF;
	}
	
	&.status-pending {
		background-color: #2196F3;
		color: #FFFFFF;
	}
	
	&.status-default {
		background-color: #FF9800;
		color: #FFFFFF;
	}
}

/* 借款明细项样式 */
.loan-detail-item {
	background-color: #FFFFFF;
	border-radius: 8rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
	border: 1rpx solid #E0E0E0;
}

.detail-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 20rpx;
	padding-bottom: 15rpx;
	border-bottom: 1rpx solid #F0F0F0;
}

.detail-number {
	font-size: 28rpx;
	font-weight: 500;
	color: #333333;
}

.detail-field {
	margin-bottom: 20rpx;
}

.field-label {
	display: block;
	font-size: 28rpx;
	color: #333333;
	margin-bottom: 15rpx;
}

.detail-value {
	padding: 20rpx;
	background-color: #FFFFFF;
	border-radius: 8rpx;
	border: 1rpx solid #E0E0E0;
}

.detail-text {
	font-size: 28rpx;
	color: #333333;
}

.detail-section {
	background-color: #F8F8F8;
	border-radius: 12rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
}

.section-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 20rpx;
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
}

/* 附件样式 */
.attachments-area {
	padding: 20rpx;
	background-color: #FFFFFF;
	border-radius: 8rpx;
	border: 1rpx solid #E0E0E0;
}

.attachments-list {
	display: flex;
	flex-direction: column;
	gap: 15rpx;
}

.file-item {
	display: flex;
	align-items: center;
	padding: 15rpx;
	background-color: #F8F8F8;
	border-radius: 8rpx;
	border: 1rpx solid #E0E0E0;
	cursor: pointer;
	transition: all 0.2s ease;
	
	&:hover {
		background-color: #F0F0F0;
		border-color: var(--u-primary);
	}
}

.file-thumbnail {
	width: 60rpx;
	height: 60rpx;
	border-radius: 6rpx;
	margin-right: 15rpx;
	flex-shrink: 0;
}

.file-icon {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #E0E0E0;
	border-radius: 6rpx;
	margin-right: 15rpx;
	flex-shrink: 0;
}

.icon-text {
	font-size: 32rpx;
	color: #666666;
}

.file-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 5rpx;
}

.file-name {
	font-size: 28rpx;
	color: #333333;
	font-weight: 500;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
	max-width: 480rpx; /* 限制最大宽度，防止溢出 */
}

.file-size {
	font-size: 24rpx;
	color: #999999;
}

.no-attachments {
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #F0F0F0;
	border: 1rpx dashed #E0E0E0;
	border-radius: 8rpx;
	padding: 20rpx;
	font-size: 28rpx;
	color: #999999;
}

.no-attachments-text {
	font-size: 28rpx;
}

.attachments-list {
	display: flex;
	flex-wrap: wrap;
	gap: 10rpx;
}

.file-item {
	display: flex;
	align-items: center;
	background-color: #F0F0F0;
	border-radius: 8rpx;
	padding: 10rpx 15rpx;
	font-size: 24rpx;
	color: #333333;
}

.file-name {
	flex: 1;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

/* 底部安全區域和按鈕 */
.safe-area-bottom {
	height: env(safe-area-inset-bottom);
	background-color: #F5F5F5;
}

.edit-button-container {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #FFFFFF;
	padding: 18rpx;
	padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
	border-top: 1rpx solid #F0F0F0;
	z-index: 99;
}

.edit-button {
	width: 100%;
	padding: 20rpx;
	background-color: var(--u-primary);
	color: #FFFFFF;
	font-size: 32rpx;
	font-weight: bold;
	border-radius: 8rpx;
	border: none;
}
</style>
